<?php
namespace app\controller;

use app\BaseController;
use think\facade\Request;
use think\facade\Db;
use think\Exception;
use think\facade\Filesystem;
use think\facade\Log;
use think\Event;
use app\event\AssetHistoriesEvent;
use think\facade\Config;
use think\facade\Http;
use think\facade\Cache;

class WechatMiniProgram extends BaseController
{

    /**
     * 获取微信小程序的 access_token
     *
     * @return \think\response\Json
     */
    public function getAccessToken()
    {
        // 从配置文件中获取 appId 和 appSecret
        $appId = Config::get('wechat.appId');
        $appSecret = Config::get('wechat.appSecret');

        // 构造请求 URL
        $url = sprintf(
            'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s',
            $appId,
            $appSecret
        );

        // 发送 HTTP GET 请求
        $response = file_get_contents($url);
        $response=json_decode($response);



        if(property_exists($response,'access_token')){
            return json(['code'=>200,'data' => $response->access_token]);
        }else{
            return json(['code'=>201,'msg' => $response->errmsg ?? 'Failed to get access_token'], 500);
        }

    }

    //获取微信小程序码
    public function getUnlimitedQrCode()
    {

        $scene=Request::param('data');
        // 获取 access_token
        $accessToken=Request::param('accessToken');

        // 构造请求 URL
        $url = sprintf(
            'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=%s',
            $accessToken
        );

        // 构造请求数据
        $postData = json_encode([
            'scene' => $scene,
            'page' => 'pages/login/login',
            'env_version' => 'trial',
            'check_path'=>false,
        ]);

       // 初始化 cURL
        $ch = curl_init($url);

       // 设置 cURL 选项
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Content-Type: application/json'
        ]);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);

        // 执行请求并获取响应
        $response = curl_exec($ch);

       // 检查请求是否成功
        if (curl_errno($ch)) {
            throw new Exception('Curl error: ' . curl_error($ch));
        }

        // 关闭 cURL 资源
        curl_close($ch);


        //判断是否是二进制数据,是二进制则说明返回了正确的图片
        if(isBinaryData($response)){
            $response=base64_encode($response);
            // 将响应数据存储在缓存中
          Cache::set($scene, ['flag' => false], 30);
            return $response;
        }else{
            $response_json=json_decode($response);
            return json(['code'=>201,'msg' => $response_json->errmsg ?? 'Failed to get access_token','errcode'=>$response_json->errcode], 500);
        }



    }
    //检查二维码缓存
    public function checkQrCodeCache()
    {
        $scene=Request::param('data');
        $cache = Cache::get($scene);
        if (is_null($cache)) {
            return json(['code'=>201,'msg' => '二维码已失效,请刷新二维码']);
        }

        if($cache['flag']==false) {
            return json(['code' => 202, 'msg' => '状态未改变，还未扫码']);
        }elseif ($cache['flag']==true){
            return json(['code' => 200, 'msg' => '扫码成功','data'=>$cache]);
        }else{
            return json(['code' => 203, 'msg' => $cache]);
        }


    }
    //使用openid登录的方法
    public function loginByOpenid()
    {
        $openid=Request::param('openid');
        $user = Db::table('user')->where('user_openid', $openid)->find();
        //检查是否在审核记录表中
        $audit = Db::table('AuditUse')->where('AuditUser_openid',$openid)->where('AuditUser_state', '未审核')->find();
        $refuse_audit = Db::table('AuditUse')->where('AuditUser_openid',$openid)->where('AuditUser_state', '已拒绝')->find();
        if ($user) {
            //检查是否被软删除
            if($user['user_deleted']==1)
            {
                return json(['code' => 403, 'msg' => '用户已被删除', ]);
            }
            //检查是否被禁用
            if($user['user_switch']==0)
            {
                //用户被禁用
                return json(['code' => 201, 'msg' => '用户已被禁用', ]);
            }
            //登陆成功插入sessionid
            $sessionID = md5(uniqid(rand(), true));
            Db::name('user')->where('user_id', $user['user_id'])->update(['user_sessionID' => $sessionID]);
            $user = Db::table('user')->where('user_openid', $openid)->find();
            // 登录成功，返回JSON响应，状态码200,并且签发token
            return json(['code' => 200, 'msg' => '登录成功', 'data' =>['token'=> signToken($user)]]);

        }else if($audit) {
            return json(['code' => 404, 'msg' => '用户已注册,请等待审核']);
        }else if($refuse_audit){
            return json(['code' => 406, 'msg' => '注册已被拒绝']);

        } else{
            // 登录失败，返回JSON响应，状态码可以根据需要自定义，这里使用401
            return json(['code' => 405, 'msg' => '用户未注册']);
        }

    }

    //微信小程序用户注册方法
    public function register()
    {
        $openid=Request::param('openid');
        $data=Request::param('data');



    }
    //当前端口关闭二维码窗口后,需要手动清除缓存
    public function clearQrCodeCache()
    {
        $scene=Request::param('data');
        $cache = Cache::get($scene);
        if (is_null($cache)) {
            return json(['code'=>201,'msg' => '二维码已失效,无需清除']);
        }

        //直接删除缓存
        Cache::delete($scene);
        return json(['code'=>200,'msg' => '清除成功']);
    }

    //扫码成功后小程序端点击登录按钮后把openid写进缓存
    public function setOpenidCache()
    {
        $scene=Request::param('scene');
        $js_code=Request::param('js_code');
        $cache = Cache::get($scene);
        //判断secen是否传入
        if(empty($scene)){
            return json(['code'=>201,'msg' => '二维码已失效,请刷新二维码']);
        }
        if (is_null($cache)) {
            return json(['code'=>204,'msg' => '二维码不正确，请扫描正确二维码']);
        }

        // 从配置文件中获取 appId 和 appSecret
        $appId = Config::get('wechat.appId');
        $appSecret = Config::get('wechat.appSecret');
        // 构造请求 URL
        $url = sprintf(
            'https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code',
            $appId,
            $appSecret,
            $js_code
        );

        // 发送 HTTP GET 请求
        $response = file_get_contents($url);
        $response=json_decode($response);
        if(property_exists($response,'openid')){
            $openid=$response->openid;
            //将openid写入缓存,并改变缓存状态
            if($cache['flag']==false) {
                Cache::set($scene, ['flag' => true,'openid'=>$openid], 30);
                return json(['code'=>200,'msg' => '扫码成功']);
            }else{
                return json(['code'=>203,'msg' => '扫码失败']);
            }
        }else{
            return json(['code'=>202,'msg' => $response->errmsg ?? 'Failed to get access_token','errcode'=>$response->errcode], 500);
        }

    }
    //判断公司代码是否正确
    public function checkCompanyCode()
    {
        $companyCode=Request::param('companyCode');
        $company = Db::table('company')->where('company_code', $companyCode)->find();
        if ($company) {
            return json(['code' => 200, 'msg' => '公司代码正确']);
        }else{
            return json(['code' => 201, 'msg' => '公司代码错误']);
        }
    }
    //用户注册
    public function registerUser()
    {
        $data=Request::param('data');
        $openid=Request::param('openid');
        if(empty($data)){
            return json(['code'=>201,'msg' => '参数错误']);
        }else{
//            $data=json_decode($data,true);
            $user = Db::table('user')->where('user_openid', $openid)->find();
            $AuditUse=Db::table('AuditUse')->where('AuditUser_openid',$openid)->find();
            //查找code代码所属的公司
            $company = Db::table('company')->where('company_code', $data['user_code'])->find();

            //检测用户名重复
            $check_user = Db::table('user')->where('user_username', $data['user_username'])->find();
            $AuditUse=Db::table('AuditUse')->where('AuditUser_username',$data['user_username'])->where('AuditUser_state','未审核')->find();
            if ($user) {
                return json(['code' => 201, 'msg' => '用户已注册']);
            }else if ($check_user|| $AuditUse){
                return json(['code' => 203, 'msg' => '用户名已存在']);

            } else if($AuditUse) {
                return json(['code' => 202, 'msg' => '用户已注册,请等待审核']);
            }else{
                $AuditUsedata['AuditUser_state']='未审核';
                $AuditUsedata['AuditUser_company_id']=$company['company_id'];
                $AuditUsedata['AuditUser_openid']=$openid;
                $AuditUsedata['AuditUser_username']=$data['user_username'];
                $AuditUsedata['AuditUser_phone']=$data['user_phone'];
                $AuditUsedata['AuditUser_name']=$data['user_name'];
                $AuditUsedata['AuditUser_sex']=$data['user_sex'];
                $AuditUsedata['AuditUser_password']=md5($data['user_password']);
                //开启事务注册
                try {
                    Db::startTrans();
                    //插入审核表
                    //var_dump($AuditUsedata);
                    Db::table('AuditUse')->insert($AuditUsedata);
                    Db::commit();
                    return json(['code' => 200, 'msg' => '注册成功,请等待管理员审核']);
                }
                catch (\Exception $e) {
                    // 回滚事务
                    Db::rollback();
                    return json(['code' => 203, 'msg' => '注册失败','err'=>$e]);
                }
            }
        }
    }

    //检测用户名是否重复
    public function checkUserName()
    {
        $user_username=Request::param('user_username');
        $user = Db::table('user')->where('user_username', $user_username)->find();
        $AuditUse=Db::table('AuditUse')->where('AuditUser_username',$user_username)->where('AuditUser_state','未审核')->find();
        if ($user||$AuditUse) {
            return json(['code' => 201, 'msg' => '用户名已存在']);
        }else{
            return json(['code' => 200, 'msg' => '用户名可用']);
        }
    }
    //绑定已有账号
    public function bindUser()
    {
        $data=Request::param('data');
        $openid=Request::param('openid');
        if(empty($data)){
            return json(['code'=>201,'msg' => '参数错误']);
        }else{

            $user = Db::table('user')->where('user_username', $data['user_bindUsername'])->where('user_password',md5($data['user_bindPassword']))->find();
            if ($user) {
                //开启事务插入openid到user表中
                try {
                    Db::startTrans();
                    //插入openid到user表中
                    Db::table('user')->where('user_id',$user['user_id'])->update(['user_openid'=>$openid]);
                    Db::commit();
                    return json(['code' => 200, 'msg' => '绑定成功']);
                }
                catch (\Exception $e) {
                    // 回滚事务
                    Db::rollback();
                    return json(['code' => 203, 'msg' => '绑定失败','err'=>$e]);
                }
            }else{
                return json(['code' => 201, 'msg' => '用户名或密码错误']);
            }
        }
    }



}